package com.zshan.clinic.web.controller;

import com.zshan.clinic.common.constant.HeaderConstant;
import com.zshan.clinic.common.entity.HeaderDTO;
import com.zshan.clinic.common.util.redis.RedisUtil;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.web.constant.WebRedisKeyPrefix;
import com.zshan.clinic.web.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * Controller公共组件
 * @author lichen
 */
@Slf4j
public abstract class AbstractController {

	@Autowired
	private HttpServletRequest httpServletRequest;

	@Autowired
	private RedisUtil redisUtil;

	public HeaderDTO getHeader(){
		HeaderDTO headerDTO = new HeaderDTO();
		headerDTO.setIp(httpServletRequest.getHeader(HeaderConstant.IP));
		headerDTO.setToken(httpServletRequest.getHeader(HeaderConstant.TOKEN));
		String clinicId = httpServletRequest.getHeader(HeaderConstant.CLINIC_ID);
		if(StringUtil.isNotBlank(clinicId)){
			headerDTO.setClinicId(Long.parseLong(clinicId));
		}
		return headerDTO;
	}



	/**
	 * 从redis中获取用户信息
	 * @return
	 */
	protected UserInfo getUserInfo(){
		HeaderDTO headerDTO = getHeader();
		UserInfo userInfo = null;
		if(headerDTO != null && StringUtil.isNotBlank(headerDTO.getToken())){
			userInfo = (UserInfo) redisUtil.get(String.format(WebRedisKeyPrefix.USER_TOKEN,headerDTO.getToken()));
		}
		return userInfo;
	}

	/**
	 * 获取登录用户ID
	 * @return
	 */
	protected Long getUserId(){
		UserInfo userInfo = getUserInfo();
		return userInfo == null ? null : userInfo.getEmpId();
	}
}
